package mydsl;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.Iterator;

public class ToString {
	private static byte[] spaces = null;
	
	private static int INCREMENT = 2;
	
	public static <E> void  writeNodeAndChildren(Position<E> subtreeRoot,
			DataOutputStream ostream, BinaryTree<E> t, int indentation) {
		try {
			// indent, then write the subtreeRoot
			ostream.write(spaces, 0, indentation);
			ostream.writeBytes(subtreeRoot + "");
			ostream.writeBytes("\n");
		} catch (java.io.IOException e) {
			System.err.println("\nAn I/O error occurred: " + e);
			return;
		}
		Iterator<Position<E>> pp = t.children((Position<E>)subtreeRoot);
		// recur on all children
		while (pp.hasNext())
			writeNodeAndChildren((Position<E>) pp.next(), ostream, t,
					indentation + INCREMENT);
	}

	public static <E> String stringfor(BinaryTree<E> t) {
		if (spaces == null) {
			spaces = new byte[200]; // tree can't be more than 100 levels deep
			for (int i = 0; i < 200; ++i)
				spaces[i] = (byte) ' ';
		}
		// the 4 below was generated entirely at random
		ByteArrayOutputStream bstr = new ByteArrayOutputStream(t.size() * 4);
		DataOutputStream ostr = new DataOutputStream(bstr);
		writeNodeAndChildren(t.root(), ostr, t, 0);
		return bstr.toString();
	}
}
